'use strict';

const BaseService = require('./base');
const modelName = 'User';
const { Op } = require('sequelize');
class RouterService extends BaseService {
  constructor(ctx) {
    super(ctx, modelName);
  }
  async getPage(where, page, pageSize) {
    return await this.ctx.model[this.modelName].findAndCountAll({
      where,
      offset: pageSize * (page - 1),
      limit: pageSize,
      order: [
        // id 降序
        ['id', 'DESC'],
      ],
      include: [
        {
          model: this.ctx.model.Role,
          as: 'role'
        }
      ]
    });
  }

  async login(username, password) {
    const user = await this.ctx.model[this.modelName].findOne({
      where: {
        username,
        password
      },
    });
    if (!user) {
      throw new Error('用户名或密码错误');
    }
    return {
      ...user.dataValues
    };
  }

  async getUserInfo(id) {
    const user = await this.ctx.model[this.modelName].findOne({
      where: {
        id
      }
    });
    if (!user) {
      throw new Error('用户不存在');
    }
    let roleUserList = await this.ctx.model.RoleUser.findAll({
      where: {
        user_id: id
      },
      include: [
        {
          model: this.ctx.model.Role,
          as: 'role'
        }
      ]
    })
    let menuIdList = []
    roleUserList.forEach(item => {
        if (item.role && item.role.menu_id) {
          let _idList = item.role.menu_id.split(',')
          menuIdList = menuIdList.concat(_idList)
        }
    })
    // 去重
    menuIdList = Array.from(new Set(menuIdList))
    console.log('menuIdList',menuIdList)
    let menuList = []
    // 角色中的menu
    if (menuIdList.length) {
      let _menuList = await this.ctx.model.Menu.findAll({
        where: {
          id: {
            [Op.in]: menuIdList
          }
        },
        order: [
          ['sort', 'ASC']
        ],
        raw: true
      })
      menuList = this.ctx.service.menu.listToTree(_menuList.map(item => {
        return {
          parentId: item.pid,
          ...item,
          visible: true
        }
      }), {
        idKey: 'id',
        pidKey: 'parentId',
        childrenKey: 'children',
      })
    }
    return {
      ...user.dataValues,
      menuList,
    };
  }

  async getUserRoles(userId) {
    const roleUserList = await this.ctx.model.RoleUser.findAll({
        where: {
          user_id: userId
        }
    })
    return roleUserList.map(item => item.role_id)
  }
  async updateUserRoles({ userId, roleIds }) {
    await this.ctx.model.RoleUser.destroy({
      where: {
        user_id: userId
      }
    })
    const res= await this.ctx.model.RoleUser.bulkCreate(roleIds.map(roleId => {
      return {
        user_id: userId,
        role_id: roleId
      }
    }))
    return res
  }
}


module.exports = RouterService;
